package utils;

import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiChatCreateRequest;
import com.dingtalk.api.request.OapiChatSendRequest;
import com.dingtalk.api.request.OapiGettokenRequest;
import com.dingtalk.api.request.OapiUserSimplelistRequest;
import com.dingtalk.api.response.OapiChatCreateResponse;
import com.dingtalk.api.response.OapiChatSendResponse;
import com.dingtalk.api.response.OapiGettokenResponse;
import com.dingtalk.api.response.OapiUserSimplelistResponse;
import com.taobao.api.ApiException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetSocketAddress;
import java.net.Proxy;
import java.util.List;

/**
 * 钉钉工具类
 * */
public class DingDingUtils {

    private static Logger logger = LoggerFactory.getLogger(DingDingUtils.class);

    //获取access_token
    public static String getAccessToken(){
        DefaultDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
        //生产设置代理
        setProxy(client);
        OapiGettokenRequest request = new OapiGettokenRequest();
        request.setCorpid(System.getenv("corp_id"));
        request.setCorpsecret(System.getenv("corp_secret"));
        request.setHttpMethod("GET");
        OapiGettokenResponse response = null;
        try {
            response = client.execute(request);
        } catch (ApiException e) {
            e.printStackTrace();
        }
        if("ok".equals(response.getErrmsg())){
            return response.getAccessToken();
        }else {
            return null;
        }
    }

    /**
     * 获取部门的用户对象
     * @param departmentId 部门id
     * 技术部：81609514；测试运维部：81615483；产品部：81677513；运维：81563515
     * @param access_token
     * */
    public static List<OapiUserSimplelistResponse.Userlist> getUser(Long departmentId,String access_token){
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/user/simplelist");
        //生产设置代理
        setProxy(client);
        OapiUserSimplelistRequest request = new OapiUserSimplelistRequest();
        request.setDepartmentId(departmentId);
        request.setOffset(0L);
        request.setSize(100L);
        request.setHttpMethod("GET");
        OapiUserSimplelistResponse response = null;
        try {
            response = client.execute(request, access_token);
        } catch (ApiException e) {
            e.printStackTrace();
        }
        if("ok".equals(response.getErrmsg())){
            return response.getUserlist();
        }else {
            return null;
        }
    }


    /**
     * 创建群聊
     * @param chatName 群名
     * @param owner 群主
     * @param userList 群员
     * @param access_token
     * @return 群id
     * */
    public static String createChat(String chatName,String owner,List<String> userList,String access_token){
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/chat/create");
        //生产设置代理
        setProxy(client);
        OapiChatCreateRequest request = new OapiChatCreateRequest();
        request.setName(chatName);
        request.setOwner(owner);
        request.setUseridlist(userList);
        //新成员是否可查看聊天历史消息 0否 1是
        request.setShowHistoryType(1L);
        OapiChatCreateResponse response = null;
        try {
            response = client.execute(request, access_token);
        } catch (ApiException e) {
            e.printStackTrace();
        }
        if("ok".equals(response.getErrmsg())){
            return response.getChatid();
        }else {
            return null;
        }
    }

    /**
     * 发送群消息
     * @param charId 群id
     * @param message 消息内容
     * @param access_token
     * */
    public static boolean sendChatMessage(String charId,String message,String access_token){
        logger.info("DingDing sendChatMessage message------>" + message);
        DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/chat/send");
        //生产设置代理
        setProxy(client);
        OapiChatSendRequest request = new OapiChatSendRequest();
        request.setChatid(charId);
        OapiChatSendRequest.Msg msg = new OapiChatSendRequest.Msg();
        msg.setMsgtype("text");
        OapiChatSendRequest.Text text = new OapiChatSendRequest.Text();
        text.setContent(message);
        msg.setText(text);
        request.setMsg(msg);
        OapiChatSendResponse response = null;
        try {
            response = client.execute(request, access_token);
        } catch (ApiException e) {
            logger.error("DingDing sendChatMessage error------>" + e.getErrMsg());
            e.printStackTrace();
        }
        if("ok".equals(response.getErrmsg())){
            return true;
        }else {
            return false;
        }
    }

    private static void setProxy(DingTalkClient client){
        String publishMode = System.getenv("PUBLISH_MODE");
        if("PRODUCT".equals(publishMode)){
            //生产设置代理
            String proxyHost = System.getProperty("http.proxyHost");
            String proxyPort = System.getProperty("http.proxyPort");
            InetSocketAddress inetSocketAddress = new InetSocketAddress(proxyHost, Integer.parseInt(proxyPort));
            Proxy proxy = new Proxy(Proxy.Type.HTTP, inetSocketAddress);
            ((DefaultDingTalkClient) client).setProxy(proxy);
        }
    }

}
